//package com.ruoyi.spot.realtime.kline.util;
//
//import okhttp3.*;
//import okio.ByteString;
//import java.io.ByteArrayInputStream;
//import java.io.IOException;
//import java.util.concurrent.CountDownLatch;
//import java.util.zip.GZIPInputStream;
//
///**
// * @program: ChainUp_Monitor_Rear
// * @description:
// * @author: Saumell
// * @create: 2024-08-06 17:00
// **/
//public class WebSocketUtilsReq {
//
//    private final OkHttpClient client;
//    private final CountDownLatch latch;
//    private String decompressedMessage;
//
//    public WebSocketUtilsReq(String URL, String REQ_PARAM) {
//        this.client = new OkHttpClient();
//        this.latch = new CountDownLatch(1);
//        this.decompressedMessage = null; // Initialize as null
//
//        Request request = new Request.Builder()
//                .url(URL)
//                .build();
//
//        WebSocketListener listener = new WebSocketListener() {
//            @Override
//            public void onOpen(WebSocket webSocket, Response response) {
////                System.out.println("Connection opened");
//                webSocket.send(REQ_PARAM);
//            }
//
//            @Override
//            public void onMessage(WebSocket webSocket, String text) {
////                System.out.println("Received message: " + text);
//                decompressedMessage = text; // Store the received message
//                closeConnection(webSocket);
//            }
//
//            @Override
//            public void onMessage(WebSocket webSocket, ByteString bytes) {
//                try {
//                    decompressedMessage = decompressGzip(bytes.toByteArray());
////                    System.out.println("Received decompressed message: " + decompressedMessage);
//                } catch (IOException e) {
////                    System.err.println("Failed to decompress message: " + e.getMessage());
//                    decompressedMessage = null; // Set to null if decompression fails
//                } finally {
//                    closeConnection(webSocket);
//                }
//            }
//
//            @Override
//            public void onFailure(WebSocket webSocket, Throwable t, Response response) {
////                System.err.println("Error: " + t.getMessage());
//                decompressedMessage = null; // Set to null if there is a failure
//                latch.countDown();
//            }
//
//            @Override
//            public void onClosed(WebSocket webSocket, int code, String reason) {
////                System.out.println("Connection closed: " + reason);
//                latch.countDown();
//            }
//        };
//
//        WebSocket webSocket = client.newWebSocket(request, listener);
//
//        // Wait for the WebSocket to close
//        try {
//            latch.await();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//
//        // Shutdown the client
//        client.dispatcher().executorService().shutdown();
//    }
//
//    private static String decompressGzip(byte[] compressed) throws IOException {
//        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(compressed);
//        GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream);
//        StringBuilder outStr = new StringBuilder();
//        byte[] buffer = new byte[1024];
//        int numRead;
//        while ((numRead = gzipInputStream.read(buffer)) != -1) {
//            outStr.append(new String(buffer, 0, numRead));
//        }
//        return outStr.toString();
//    }
//
//    private static void closeConnection(WebSocket webSocket) {
//        webSocket.close(1000, "Closing connection after receiving message");
//    }
//
//    public String getDecompressedMessage() {
//        return decompressedMessage; // Return the message or null if not received
//    }
//}
package com.ruoyi.util;

import okhttp3.*;
import okio.ByteString;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.zip.GZIPInputStream;

/**
 * @program: ChainUp_Monitor_Rear
 * @description:
 * @author: Saumell
 * @create: 2024-08-06 17:00
 **/
public class WebSocketUtilsReq {

    private final OkHttpClient client;
    private final CountDownLatch latch;
    private String decompressedMessage;
    private WebSocket webSocket; // Add a WebSocket instance variable

    public WebSocketUtilsReq(String URL, String REQ_PARAM) {
        this.client = new OkHttpClient();
        this.latch = new CountDownLatch(1);
        this.decompressedMessage = null; // Initialize as null

        Request request = new Request.Builder()
                .url(URL)
                .build();

        WebSocketListener listener = new WebSocketListener() {
            @Override
            public void onOpen(WebSocket webSocket, Response response) {
                webSocket.send(REQ_PARAM);
            }

            @Override
            public void onMessage(WebSocket webSocket, String text) {
                decompressedMessage = text; // Store the received message
                closeConnection(webSocket);
            }

            @Override
            public void onMessage(WebSocket webSocket, ByteString bytes) {
                try {
                    decompressedMessage = decompressGzip(bytes.toByteArray());
                } catch (IOException e) {
                    decompressedMessage = null; // Set to null if decompression fails
                } finally {
                    closeConnection(webSocket);
                }
            }

            @Override
            public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                decompressedMessage = null; // Set to null if there is a failure
                latch.countDown();
            }

            @Override
            public void onClosed(WebSocket webSocket, int code, String reason) {
                latch.countDown();
            }
        };

        this.webSocket = client.newWebSocket(request, listener); // Initialize the WebSocket instance variable

        // Wait for the WebSocket to close
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // Shutdown the client
        client.dispatcher().executorService().shutdown();
    }

    private static String decompressGzip(byte[] compressed) throws IOException {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(compressed);
        GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream);
        StringBuilder outStr = new StringBuilder();
        byte[] buffer = new byte[1024];
        int numRead;
        while ((numRead = gzipInputStream.read(buffer)) != -1) {
            outStr.append(new String(buffer, 0, numRead));
        }
        return outStr.toString();
    }

    private static void closeConnection(WebSocket webSocket) {
        webSocket.close(1000, "Closing connection after receiving message");
    }

    public void closeConnection() {
        if (webSocket != null) {
            webSocket.close(1000, "Closing connection in finally block");
        }
    }

    public String getDecompressedMessage() {
        return decompressedMessage; // Return the message or null if not received
    }
}